import React, { Component } from 'react';
import { Table, message, Tag, Tabs, Tooltip } from 'antd';
import { InfoCircleOutlined, QuestionCircleTwoTone } from '@ant-design/icons';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { getExamList, examEmpList } from '../../api3';
import { publishStatus } from '../../api/exam';
import HasPermi from '../../componentJsx/common/hasPermi';
import NewModal from '../../componentJsx/common/NewModal';
import AdvancedSearchForm from '../../componentJsx/common/searchForm';
import 'antd/dist/antd.css';
// import { getUrl } from '../../utils';
import '../../componentCss/component.css';
//import './index.css';
//字典
import { getDictionaryLabel } from '../../rudexRou/OperatesCookie.js';
// const { Text } = Typography;
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      publishModalVisible: false,
      publishScoreModalVisible: false,
      confirmLoading: false, //确认按钮异步等待
      tableLoading: false, //表格等待
      selectedRowKeys: [], //最新表格多选
      selectedRows: [],
      //分页
      total: 0,
      pageSize: 10,
      page: 1,
      examtotal: 0,
      exampageSize: 10,
      exampage: 1,
      //数据
      tableData: [], //最新数据
      examData: [],
      //表格列
      tableColumns: [
        {
          title: '考试名称',
          dataIndex: 'name',
          key: 'name',
          width: 240,
          fixed: 'left',
          ellipsis: true,
        },
        {
          title: '考试类型',
          dataIndex: 'open',
          key: 'open',
          ellipsis: true,
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('testExamType', text) : text,
        },
        {
          title: '考试级别',
          dataIndex: 'level',
          key: 'level',
          width: 80,
          ellipsis: true,
          render: (text) =>
            text ? getDictionaryLabel('examLevel', text) : text,
        },
        {
          title: '考试语言',
          dataIndex: 'language',
          key: 'language',
          ellipsis: true,
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('language', text) : text,
        },
        {
          title: '有效期',
          dataIndex: 'validityBeginDate',
          key: 'validityBeginDate',
          ellipsis: true,
          width: 200,
          render: (t, r) =>
            t
              ? moment(r.validityBeginDate).format('YYYY-MM-DD') +
                ' 至 ' +
                moment(r.validityEndDate).format('YYYY-MM-DD')
              : r.validity == '1'
              ? '永久有效'
              : '一次性',
        },
        {
          title: '考试开始时间',
          dataIndex: 'startTime',
          key: 'startTime',
          ellipsis: true,
          width: 160,
          render: (text) =>
            text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : text,
        },
        {
          title: '考试时长(min)',
          dataIndex: 'duration',
          key: 'duration',
          ellipsis: true,
          width: 120,
        },
        {
          title: '考试次数',
          dataIndex: 'count',
          key: 'count',
          ellipsis: true,
          width: 80,
          render: (t) => (t == '0' ? '无限次' : t),
        },
        {
          title: '总分',
          dataIndex: 'totalScore',
          key: 'totalScore',
          ellipsis: true,
          width: 60,
        },
        {
          title: '及格分',
          dataIndex: 'passScore',
          key: 'passScore',
          ellipsis: true,
          width: 70,
        },
        // {
        //   title: '题目数',
        //   dataIndex: 'questionList',
        //   key: 'questionList',
        //   ellipsis: true,
        //   width: 80,
        //   render: (t, r) => (r.questionList ? r.questionList.length : ''),
        // },
        {
          title: '创建人',
          dataIndex: 'createEmpName',
          key: 'createEmpName',
          ellipsis: true,
          width: 140,
          render: (t, r) => t + `(${r.createEmpNo})`,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          ellipsis: true,
          width: 150,
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          ellipsis: true,
          width: 150,
          // render: (text) =>
          // text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : text,
        },
        {
          title: (
            <Tooltip title='已发布/已阅人数'>
              发布进度 <QuestionCircleTwoTone />
            </Tooltip>
          ),
          dataIndex: 'publishCount',
          key: 'publishCount',
          ellipsis: true,
          width: 110,
          align: 'center',
          fixed: 'right',
          render: (text, record) => text + ' / ' + record.joinTotalCount,
        },
        {
          title: '操作',
          dataIndex: 'handle',
          ellipsis: true,
          width: 70,
          fixed: 'right',
          align: 'center',
          render: (_, record) => (
            <HasPermi
              bottonData={{
                type: 'link',
                size: 'small',
                interceptor: 'tmfsExamPlatform:myExam:join',
                clickFn: () => this.showPublishModal(record.id, record),
                text: '发布',
              }}
            />
          ),
        },
      ],
      examColumns: [
        {
          title: '工号',
          dataIndex: 'empNo',
          key: 'empNo',
          width: 120,
          fixed: 'left',
          ellipsis: true,
        },
        {
          title: '姓名',
          dataIndex: 'empName',
          key: 'empName',
          width: 120,
          ellipsis: true,
          fixed: 'left',
        },
        {
          title: '部门BD',
          dataIndex: 'orgBdName',
          key: 'orgBdName',
          ellipsis: true,
          width: 270,
        },
        {
          title: '部门BU',
          dataIndex: 'orgBuName',
          key: 'orgBuName',
          ellipsis: true,
          width: 270,
        },
        {
          title: '部门CU',
          dataIndex: 'orgCuName',
          key: 'orgCuName',
          ellipsis: true,
          width: 270,
        },
        {
          title: '地域',
          dataIndex: 'regionName',
          key: 'regionName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '考试状态',
          dataIndex: 'examStatus',
          key: 'examStatus',
          ellipsis: true,
          align: 'center',
          width: 100,
          render: (t, r) => {
            switch (t) {
              case 0:
                return <Tag color='#f50'>未考</Tag>;
              case 1:
                return <Tag color='#2db7f5'>考试中</Tag>;
              case 2:
                return <Tag color='#87d068'>已完成</Tag>;
              case 3:
                return <Tag color='#cd201f'>缺考</Tag>;
              default:
                break;
            }
          },
        },
        {
          title: '阅卷状态',
          dataIndex: 'markingStatus',
          key: 'markingStatus',
          ellipsis: true,
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('markingStatus', text) : text,
        },
        {
          title: '参考时间',
          dataIndex: 'startTime',
          key: 'startTime',
          ellipsis: true,
          width: 160,
        },
        {
          title: '考试成绩',
          dataIndex: 'score',
          key: 'score',
          ellipsis: true,
          width: 80,
        },
        {
          title: '是否通过',
          dataIndex: 'pass',
          key: 'pass',
          ellipsis: true,
          width: 80,
          render: (text) => (text ? (text == '0' ? '未通过' : '通过') : text),
        },
        {
          title: '发布状态',
          dataIndex: 'status',
          key: 'status',
          ellipsis: true,
          width: 80,
          render: (text) =>
            text ? getDictionaryLabel('testExamStatus', text) : text,
        },
        {
          title: '阅卷人',
          dataIndex: 'examinerName',
          key: 'examinerName',
          ellipsis: true,
          width: 100,
          render: (text, record) =>
            record.markingStatus == '1' && !text ? '系统' : text,
        },
        {
          title: '阅卷时间',
          dataIndex: 'markingTime',
          key: 'markingTime',
          ellipsis: true,
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'handle',
          ellipsis: true,
          width: 80,
          fixed: 'right',
          align: 'center',
          render: (_, record) => (
            <>
              <HasPermi
                bottonData={{
                  type: 'link',
                  size: 'small',
                  interceptor: 'tmfsExamPlatform:publishScore:publish',
                  clickFn: () => this.showPublishScoreModal(record),
                  text: '发布成绩',
                  disabled: record.status == '1' || record.markingStatus == '0',
                }}
              />
            </>
          ),
        },
      ],
      //查询条件
      searchData: {},
      searchEmpData: { markingStatus: '1', status: '0' },
      searchForm: [
        {
          type: 'input',
          name: '考试名称',
          code: 'name',
          maxLength: 50,
        },
        {
          type: 'select',
          name: '考试级别',
          code: 'level',
          options: getDictionaryLabel('examLevel'),
        },
      ],
      searchEmpForm: [
        {
          type: 'input',
          name: '工号/姓名',
          code: 'empNoOrName',
          placeholder: '工号/姓名',
          maxLength: 50,
        },
        {
          type: 'select',
          name: '发布状态',
          code: 'status',
          options: [
            { code: '0', label: '未发布' },
            { code: '1', label: '已发布' },
          ],
        },
        {
          type: 'select',
          name: '阅卷状态',
          code: 'markingStatus',
          options: getDictionaryLabel('markingStatus'),
        },
      ],
      // 查询条件项配置
      activeKey: '1',
      examId: null,
      examInfo: null,
      examLoading: false,
    };
  }
  //考试列表查询
  getData = (type) => {
    this.setState({ tableLoading: true });
    let searchData = this.state.searchData;
    let data = {};
    for (const key in searchData) {
      if (searchData[key] || searchData[key] === 0) {
        data[key] = searchData[key];
      }
    }
    data.type = type;
    data.pageSize = this.state.pageSize;
    data.currentPage = this.state.page;
    getExamList(data)
      .then((res) => {
        if (res.data.code === 200) {
          if (res.data.data) {
            this.setState({
              total: res.data.data.total,
              tableData: res.data.data.list,
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          } else {
            this.setState({
              total: 0,
              tableData: [],
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          }
        } else {
          this.setState({ tableLoading: false });
          message.error(res.data.message || '查询数据失败!');
        }
      })
      .catch((err) => {
        this.setState({ tableLoading: false });
        message.error('查询数据失败!');
      });
  };
  //发布成绩
  publishScores = () => {
    this.buttonLoading(true);
    publishStatus({
      ids: this.state.selectedRowKeys.join(','),
      publishStatus: '1',
    }).then((res) => {
      if (res.data.code === 200) {
        message.success('发布成功!');
        this.setState({ selectedRowKeys: [], selectedRows: [] });
        this.initExamPage(this.state.examId);
        this.getData(this.state.activeKey);
      } else {
        message.error(res.data.message || '操作失败!');
      }
      this.hiddenPublishScoreModal();
    });
  };
  //查询未发布成绩
  initExamPage(examId) {
    const params = {
      currentPage: this.state.exampage,
      pageSize: this.state.exampageSize,
      examId: examId,
      // markingStatus: '1',
      ...this.state.searchEmpData,
    };
    this.setState({ examLoading: true });
    examEmpList(params).then((res) => {
      const dataList = [];
      // console.log(res.data);
      if (res.data.code === 200) {
        const list = res.data.data.list;
        list.forEach((item) => {
          if (item && item.examScoreList && item.examScoreList.length > 1) {
            const children = item.examScoreList.slice(
              1,
              item.examScoreList.length
            );
            children.forEach((child) => {
              child = Object.assign(child, {
                orgBdName: item.orgBdName,
                orgBgName: item.orgBgName,
                orgBuName: item.orgBuName,
                orgCuName: item.orgCuName,
                regionName: item.regionName,
                empName: item.empName,
                empNo: item.empNo,
              });
            });
            item = Object.assign(item, item.examScoreList[0]);
            item.children = children;
          } else {
            Object.assign(item, item.examScoreList[0]);
          }
          dataList.push(item);
        });
        this.setState({ examData: dataList, examtotal: res.data.data.total });
      }
      this.setState({ examLoading: false });
    });
  }
  //搜索框
  execSearch = (data) => {
    this.setState({ searchData: data, page: 1, tableData: [] }, () => {
      this.getData(this.state.activeKey);
    });
  };
  execSearchEmp = (data) => {
    // console.log(data);
    this.setState(
      {
        searchEmpData: data,
        exampage: 1,
        selectedRowKeys: [],
        selectedRows: [],
      },
      () => {
        this.initExamPage(this.state.examId);
      }
    );
  };
  //修改页数changePage
  changePage = (page, pageSize) => {
    let activeKey = this.state.activeKey;
    this.setState({ page, pageSize }, () => {
      this.getData(activeKey);
    });
  };
  changeExamPage = (exampage, exampageSize) => {
    this.setState({ exampage, exampageSize }, () => {
      this.initExamPage(this.state.examId);
    });
  };
  //设置按钮加载动画开关
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  //隐藏模态框
  hiddenModal = () => {
    this.setState({
      publishModalVisible: false,
      confirmLoading: false, //确认按钮异步等待
      record: null,
      examId: null,
      examInfo: {},
      examData: [],
      examtotal: 0,
      exampageSize: 10,
      exampage: 1,
      selectedRowKeys: [], //最新表格多选
      selectedRows: [],
      searchEmpData: { markingStatus: '1', status: '0' },
    });
  };
  hiddenPublishScoreModal = () => {
    this.setState({
      publishScoreModalVisible: false,
      confirmLoading: false,
    });
  };
  //显示模态框
  showPublishScoreModal = (record) => {
    if (record !== -1) {
      this.setState({
        publishScoreModalVisible: true,
        selectedRowKeys: [record.id],
        selectedRows: [record],
      });
    } else {
      this.setState({
        publishScoreModalVisible: true,
      });
    }
  };
  showPublishModal = (examId, examInfo) => {
    this.initExamPage(examId);
    this.setState({
      examId,
      examInfo,
      publishModalVisible: true,
    });
  };
  //tab页切换
  tabChange = (activeKey) => {
    this.setState(
      {
        activeKey,
        pageSize: 10,
        page: 1,
        tableData: [],
        searchData: {},
      },
      () => {
        this.getData(activeKey);
      }
    );
  };
  //表格多选=
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };
  //防抖
  debounce(fn, ms = 500) {
    let timeoutId;
    return function() {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => {
        fn.apply(this, arguments);
      }, ms);
    };
  }
  componentWillMount() {
    this.getData('1');
  }
  componentDidMount() {}
  //组件销毁时取消setState
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: record.status == '1' || record.markingStatus == '0',
        // name: record.name,
      }),
    };
    //多选行配置
    return (
      <div id='evaluate'>
        <div className='myProjectsBody'>
          <Tabs onChange={this.tabChange}>
            <Tabs.TabPane tab='考试成绩' key='1'>
              {this.state.activeKey === '1' ? (
                <div>
                  <div className='bigContent1'>
                    <AdvancedSearchForm
                      execSearch={this.execSearch}
                      formData={this.state.searchForm}
                    />
                  </div>
                  <div className='tabstyle'>
                    <div className='bigContent1' id='projectDetail'>
                      <div className='tableDiff'>
                        <Table
                          rowKey='id'
                          loading={this.state.tableLoading}
                          style={{ marginTop: 10 }}
                          scroll={{ x: '100' }}
                          rowSelection={null}
                          columns={this.state.tableColumns}
                          dataSource={this.state.tableData}
                          pagination={{
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            current: this.state.page,
                            showSizeChanger: true,
                            onChange: this.changePage,
                            onShowSizeChange: this.changePageSize,
                            showTotal: (total) => '共 ' + total + ' 条',
                          }}
                          bordered
                        />
                      </div>
                    </div>
                  </div>
                </div>
              ) : null}
            </Tabs.TabPane>

            <Tabs.TabPane tab='练习成绩' key='0'>
              {this.state.activeKey === '0' ? (
                <div>
                  <div className='bigContent1'>
                    <AdvancedSearchForm
                      execSearch={this.execSearch}
                      formData={this.state.searchForm}
                    />
                  </div>
                  <div className='tabstyle'>
                    <div className='bigContent1' id='projectDetail'>
                      <div className='tableDiff'>
                        <Table
                          rowKey='id'
                          loading={this.state.tableLoading}
                          style={{ marginTop: 10 }}
                          scroll={{ x: '100' }}
                          rowSelection={null}
                          columns={this.state.tableColumns}
                          dataSource={this.state.tableData}
                          pagination={{
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            current: this.state.page,
                            showSizeChanger: true,
                            onChange: this.changePage,
                            onShowSizeChange: this.changePageSize,
                            showTotal: (total) => '共 ' + total + ' 条',
                          }}
                          bordered
                        />
                      </div>
                    </div>
                  </div>
                </div>
              ) : null}
            </Tabs.TabPane>
          </Tabs>
        </div>
        {/* 详情modal */}
        <NewModal
          modalOptions={{
            width: '90%',
            title: '发布成绩',
            visible: this.state.publishModalVisible,
            onCancel: this.hiddenModal,
            destroyOnClose: true,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [],
          }}
        >
          <div>
            <AdvancedSearchForm
              execSearch={this.execSearchEmp}
              formData={this.state.searchEmpForm}
              initialValues={{ markingStatus: '1', status: '0' }}
            />
            <HasPermi
              bottonData={{
                type: 'primary',
                interceptor: 'tmfsExamPlatform:publishScore:publish',
                clickFn: () => this.showPublishScoreModal(-1),
                text: '发布',
                disabled:
                  this.state.selectedRowKeys &&
                  this.state.selectedRowKeys.length > 0
                    ? false
                    : true,
              }}
            />
            <Table
              rowKey='id'
              size='small'
              loading={this.state.examLoading}
              style={{ marginTop: 10 }}
              scroll={{ x: '100' }}
              rowSelection={{ type: 'checkbox', ...rowSelection }}
              columns={this.state.examColumns}
              dataSource={this.state.examData}
              pagination={{
                total: this.state.examtotal,
                pageSize: this.state.exampageSize,
                current: this.state.exampage,
                showSizeChanger: true,
                onChange: this.changeExamPage,
                showTotal: (total) => '共 ' + total + ' 条',
              }}
              bordered
            />
          </div>
        </NewModal>
        {/* 发布确认modal */}
        <NewModal
          modalOptions={{
            width: '400px',
            title: '发布成绩',
            visible: this.state.publishScoreModalVisible,
            onCancel: this.hiddenPublishScoreModal,
            destroyOnClose: true,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenPublishScoreModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.publishScores,
                text: '确定',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <InfoCircleOutlined
            style={{
              fontSize: '28px',
              color: '#1890FF',
              float: 'left',
              backgroundColor: '#29F2',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              height: 44,
              lineHeight: '44px',
            }}
          >
            确认发布选中的成绩？
          </div>
        </NewModal>
      </div>
    );
  }
}
